// 节点间通路。给定有向图，设计一个算法，找出两个节点之间是否存在一条路径。

// 示例1:

//  输入：n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
//  输出：true
// 示例2:

//  输入：n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
//  输出 true
// 提示：

// 节点数量n在[0, 1e5]范围内。
// 节点编号大于等于 0 小于 n。
// 图中可能存在自环和平行边。

#include "stdc++.h"

// 从后往前找
class Solution {
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
        for (auto& v : graph) {
            swap(v[0], v[1]);
        }
        return dfs(graph, target, start, -1);
    }
    // pre 深搜时记录上一个节点，可以解决自环和平行边造成的死循环
    bool dfs(vector<vector<int>>& graph, int start, const int& target, int pre) {
        if (start == target) {
            return true;
        }
        for (auto& v : graph) {
            if (v[0] == start && v[1] != pre) {
                if (dfs(graph, v[1], target, start)) {
                    return true;
                }
            }
        }
        return false;
    }
};

/* dfs
建立邻接表
*/
class Solution {
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
        vector<vector<int>> neighbors(n, vector<int>{});
        for (auto& v : graph) {
            neighbors[v[0]].push_back(v[1]);
        }
        vector<bool> visited(n, false);
        return dfs(neighbors, visited, start, target);
    }
    bool dfs(const vector<vector<int>>& neighbors, vector<bool>& visited, const int& start, const int& target) {
        if (start == target) {
            return true;
        }
        visited[start] = true;
        for (auto& v : neighbors[start]) {
            if (visited[v] == false && dfs(neighbors, visited, v, target) == true) {
                return true;
            }
        }
        return false;
    }
};

/* bfs
建立邻接表
*/
class Solution {
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
        vector<vector<int>> neighbors(n, vector<int>{});
        for (auto& v : graph) {
            neighbors[v[0]].push_back(v[1]);
        }
        vector<bool> visited(n, false);
        queue<int> q{};
        q.push(start);
        while (!q.empty()) {
            int cur = q.front();
            if (cur == target) {
                return true;
            }
            q.pop();
            visited[cur] = true;
            for (auto& neighbor : neighbors[cur]) {
                if (visited[neighbor] == false) {
                    q.push(neighbor);
                }
            }
        }
        return false;
    }
};